﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using Oracle.Read;
using System.Text.RegularExpressions;

namespace Oracle.Lexer;

[Order(2)]
public class IfLexer : BaseLexer
{
    public override bool Check()
        => Txt.StartsWith("IF ") || Txt.StartsWith("IF(");

    protected override BaseCodeEntity Run()
    {
        var arr = Txt.TrimSplit('÷');      
        var head = Regex.Match(arr[0], "IF(.*)THEN").Result("$1").Trim();
        var entity = new IfCodeEntity(SqlFactory.Create(head).Execute());
        var elslist = new List<List<string>>();
        var body = new List<string>();
        var elfbody = new List<string>();
        var ebody = new List<string>();
        int ifs = 0;
        int mark = 0;
        foreach (var item in arr)
        {
            if (item.StartsWith("IF ") || item.StartsWith("IF(")) ifs++;
            if (item.StartsWith("END IF"))
            {
                ifs--;
                if (ifs == 0) break;
            }
            if (ifs == 1)
            {
                if (item.StartsWith("ELSIF ") || item.StartsWith("ELSIF("))
                {
                    if (elfbody.Count > 0) elslist.Add(elfbody);
                    elfbody = new List<string>
                    {
                        item
                    };
                    mark = 1;
                    continue;
                }
                else if (item.StartsWith("ELSE"))
                {
                    ebody.Add(item[4..].Trim());
                    mark = 2;
                    continue;
                }
            }
            if (mark == 0) body.Add(item);
            else if (mark == 1) elfbody.Add(item);
            else ebody.Add(item);
        }
        body.RemoveAt(0);
        var reader = new SqlLineRead();
        reader.Read(body);
        while (reader.HasNext)
        {
            entity.Body.Add(SqlFactory.Create(reader.Next).Execute());
        }
        if (elslist.Count > 0)
        {
            entity.ElseIf = new();
            foreach (var el in elslist)
            {
                string ift = string.Join("÷", el);
                ift = ift[3..].Trim();
                entity.ElseIf.Add(SqlFactory.Create(ift).Execute());
            }
        }
        if (ebody.Count > 0)
        {
            entity.Else = new();
            reader = new SqlLineRead();
            reader.Read(ebody);
            while (reader.HasNext)
            {
                entity.Else.Add(SqlFactory.Create(reader.Next).Execute());
            }
        }
        return entity;
    }
}
